<template>
  <a-drawer
    title=""
    :width="1355"
    :visible="visible"
    :body-style="{ paddingBottom: '80px', paddingTop: '0' }"
    :closable="false"
    @close="onClose"
  >
    <a-page-header
      style="transform: translateX(-16px)"
      :title="standardInfo.name"
      :sub-title="
        '标准生效时间：' +
        standardInfo.valid_time +
        '~' +
        standardInfo.expire_time
      "
    >
      <div class="content">
        <div class="main">
          <a-descriptions size="small" :column="4">
            <a-descriptions-item label="计费模式">{{
              standardInfo.modeText ? standardInfo.modeText : "暂无"
            }}</a-descriptions-item>
            <a-descriptions-item label="单价"
              >￥{{ standardInfo.unit_price }}
              <a-tag
                v-if="standardInfo.unitText"
                :bordered="false"
                color="green"
                >x {{ standardInfo.unitText }}</a-tag
              ></a-descriptions-item
            >
            <a-descriptions-item label="状态">
              <a-tag :color="standardInfo.status == 1 ? '#87d068' : '#f50'">{{
                standardInfo.status == 1 ? "生效中" : "已失效"
              }}</a-tag>
            </a-descriptions-item>

            <a-descriptions-item label="绑定对象">
              <a-tag v-if="standardInfo.bind_object === 2" color="cyan">
                <template #icon>
                  <CarOutlined />
                </template>
                {{ standardInfo.bindOjbectText }}
              </a-tag>
              <a-tag v-if="standardInfo.bind_object === 1" color="blue">
                <template #icon>
                  <HomeOutlined />
                </template>
                {{ standardInfo.bindOjbectText }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </div>
    </a-page-header>

    <div class="top_search">
      <div class="search_con">
        费用类型：
        <a-cascader
          v-if="visible"
          v-model:value="searchForm.keyword"
          :options="costTypeList"
          placeholder="请选择费用类型"
          :load-data="getCostTypeSub"
        />
        <a-button style="margin-left: 10px" type="primary" @click="searchThis"
          >查询</a-button
        >
        <a-button style="margin-left: 10px" type="default" @click="clearSearch"
          >清空</a-button
        >
      </div>
      <a-button
        type="primary"
        @click="generateBills"
        :disabled="standardInfo.status != 1"
      >
        <template #icon>
          <PlusOutlined />
        </template>
        生成账单
      </a-button>
    </div>
    <div class="table_list">
      <a-table
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        :loading="tableLoading"
        :dataSource="tableList"
        :columns="tableColumns"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'bill_cost_type'">
            <span
              >{{ record.bill_cost_type.bigName }} /{{
                record.bill_cost_type.name
              }}
            </span>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="bindList(record)"
              >查看绑定{{
                standardInfo.bind_object == 1 ? "房间" : "车位"
              }}</a-button
            >
          </template>
        </template>
      </a-table>
    </div>

    <generateOrder
      :visible="generateVisible"
      @close="closeGenerate"
      :standardInfo="standardInfo"
      :charges_id="charges_id"
    />
    <roomList
      :bindObject="standardInfo?.bind_object || 0"
      :visible="bindVisible"
      @close="closeBind"
      :orderInfo="orderInfo"
    />
  </a-drawer>
</template>

<script>
import { message } from "ant-design-vue";
import {
  PlusOutlined,
  CheckOutlined,
  HomeOutlined,
  CarOutlined,
} from "@ant-design/icons-vue";
import { defineComponent, reactive, ref, watch, toRefs } from "vue";
import generateOrder from "./generateOrder.vue";
import request from "../../../../common/utils/request";
import { useRoute, useRouter } from "vue-router";
import roomList from "./roomList.vue";
const tableWidth = 150;

const CYCLE_COST = [
  {
    title: "费用类型",
    dataIndex: "bill_cost_type",
    key: "bill_cost_type",
    width: tableWidth + 70,
    fixed: "left",
  },
  {
    title: "绑定日期",
    dataIndex: "created_at",
    key: "created_at",
    width: tableWidth + 70,
  },
  {
    title: "账单开始日期",
    dataIndex: "start_date",
    key: "start_date",
    width: tableWidth,
  },
  {
    title: "账单结束日期",
    dataIndex: "end_date",
    key: "end_date",
    width: tableWidth,
  },
  {
    title: "计费(和拆分)规则",
    dataIndex: "dailyUnitPriceAndMonthRule",
    key: "dailyUnitPriceAndMonthRule",
    width: tableWidth + 200,
  },
  {
    title: "单价规则",
    dataIndex: "unitTxt",
    key: "unitTxt",
    width: tableWidth,
  },
  {
    title: "拆分周期",
    dataIndex: "payCycle",
    key: "payCycle",
    width: tableWidth,
  },
  {
    title: "付款时间规则",
    dataIndex: "payDailyTxt",
    key: "payDailyTxt",
    width: tableWidth + 20,
  },
  {
    title: "绑定小区",
    dataIndex: "village_name",
    key: "village_name",
    width: tableWidth,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: tableWidth,
    fixed: "right",
  }
]

const ONE_TIME_EXPENSES = [
  {
    title: "费用类型",
    dataIndex: "bill_cost_type",
    key: "bill_cost_type",
    width: tableWidth + 70,
    fixed: "left",
  },
  {
    title: "绑定日期",
    dataIndex: "created_at",
    key: "created_at",
    width: tableWidth + 70,
  },
  {
    title: "账单开始日期",
    dataIndex: "start_date",
    key: "start_date",
    width: tableWidth,
  },
  {
    title: "账单结束日期",
    dataIndex: "end_date",
    key: "end_date",
    width: tableWidth,
  },
  {
    title: "单价规则",
    dataIndex: "unitTxt",
    key: "unitTxt",
    width: tableWidth,
  },
  {
    title: "绑定小区",
    dataIndex: "village_name",
    key: "village_name",
    width: tableWidth,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: tableWidth,
    fixed: "right",
  }
]
export default defineComponent({
  emits: ["close"],
  components: {
    PlusOutlined,
    generateOrder,
    HomeOutlined,
    CarOutlined,
    roomList,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    standardInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, context) {
    const router = useRouter();
    const state = reactive({
      charges_id: 0,
      costTypeList: [],
      searchForm: {
        keyword: null,
      },
      tableLoading: false,
      pagination: {
        current: 1,
        pagiSize: 10,
        showSizeChanger: true,
        showTotal: (total, range) => `总数: ${total} 个`,
      },
      tableList: [],
      tableColumns: [],

      generateVisible: false,
      bindVisible: false,
      orderInfo: {},
    });

    const onClose = () => {
      state.searchForm.keyword = null;
      context.emit("close");
    };

    const searchThis = () => {
      getTableList();
    };

    const clearSearch = () => {
      state.searchForm = {
        keyword: null,
      };
      state.pagination.current = 1;
      getTableList();
    };

    const handleTableChange = ({ current, pageSize }) => {
      state.pagination.current = current;
      state.pagination.pagiSize = pageSize;
      getTableList();
    };

    const getTableList = () => {
      let params = {};
      params.page = state.pagination.current;
      params.pageSize = state.pagination.pagiSize;
      if (state.searchForm.keyword && state.searchForm.keyword[1]) {
        params.bill_cost_type_id = state.searchForm.keyword[1];
      }
      if (props.standardInfo.id) {
        params.charges_id = props.standardInfo.id;
      }
      state.tableLoading = true;
      request
        .get("/org", "/standard/charge/list", params)
        .then((res) => {
          state.pagination.total = res.result.total;
          state.tableList = res.result.data;
          state.tableLoading = false;
        })
        .catch((err) => {
          state.tableLoading = false;
        });
    };

    const generateBills = () => {
      state.generateVisible = true;
    };

    const closeGenerate = (flag) => {
      state.generateVisible = false;
      state.charges_id = 0;
      if (flag) {
        getTableList();
      }
    };

    const lookOrderList = (record) => {
      router.push({
        name: "billList",
      });
    };

    const getCostCategory = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          state.costTypeList = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
        .get("/org", "/bill/costList", {
          page: 1,
          limit: 9999,
          category_id: targetOption.value,
          status: 1,
        })
        .then((res) => {
          if (res.list) {
            targetOption.loading = false;
            targetOption.children = res.list.map((item) => ({
              label: item.name,
              value: item.id,
              isLeaf: true,
            }));
            state.costTypeList = [...state.costTypeList];
          }
        });
    };

    const bindList = (record) => {
      state.orderInfo = record;
      state.bindVisible = true;
    };

    const closeBind = () => {
      state.orderInfo = {};
      state.bindVisible = false;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val && props.standardInfo.id) {
          state.tableColumns = props.standardInfo.cash_type == 1 ? CYCLE_COST : ONE_TIME_EXPENSES
          getCostCategory();
          getTableList();
        }
      }
    );

    return {
      onClose,
      ...toRefs(state),
      searchThis,
      clearSearch,
      handleTableChange,
      generateBills,
      closeGenerate,
      lookOrderList,
      closeBind,
      bindList,
      getCostTypeSub,
      CYCLE_COST,
      ONE_TIME_EXPENSES,
    };
  },
});
</script>

<style lang="less" scoped>
.top_search {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;

  .search_con {
    display: flex;
    align-items: center;
  }
}

.table_list {
  margin-top: 20px;
}
</style>
